package fr.upmc.Utils;

import fr.upmc.tep.LTree.LNode;
import fr.upmc.tep.LTree.LTree;

public class LParser {

	private LTree tree;
	private String expression;
	
	public LTree getTree() {
		return tree;
	}

	public void setTree(LTree tree) {
		this.tree = tree;
	}

	public String getExpression() {
		return expression;
	}

	public void setExpression(String expression) {
		this.expression = expression;
	}

	public LParser(String exp) {
		this.expression = exp;
		createTree();
	}
	
	public void createTree() {		
		LTree lt = new LTree();	
		
		System.out.println("Expression: " + this.expression + "\n");
		
		lt.setRootNode(createNode(this.expression));		
		this.tree = lt;
	}
	
	public LNode createNode(String exp) {		
		LNode node = new LNode();
		if(exp.contains("(")) {
			
			int middle = findRightExpression(exp);
			
			System.out.println(middle);
			
			String left = exp.substring(0, middle);
			String right = exp.substring(middle+1, exp.length()-1);
			
			System.out.println("Left: " + left);
			System.out.println("Right: " + right);
			
			node.setValue("^");
			node.setLeftNode(createNode(left));
			node.setRightNode(createNode(right));
		}
		else {
			node.setValue(exp);
		}
		return node;
	}
	
	public int findRightExpression(String exp) {
		int i = exp.length() - 1;
		int count = 0;
		while(i >= 0) {
			if(exp.charAt(i) == ')')
				count ++;
			else if(exp.charAt(i) == '(') {
				count --;
				if(count == 0)
					break;
			}
			i--;
		}
		return i;
	}
}
